package com.xuecheng.content.services.service.impl;

import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.services.mapper.CourseCategoryMapper;
import com.xuecheng.content.services.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> selectTreeNodes(String id) {

        //Mapper层递归查询出分类信息
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);

        //找到每个节点的子结点，最终封装成List<CourseCategoryTreeDto>

        //先将list转为map，key就是节点的id，value就是CourseCategoryTreeDto对象，目的是方便从节点获取对象
        Map<String, CourseCategoryTreeDto> mapTemp = courseCategoryTreeDtos.stream()
                .filter(item -> !id.equals(item.getId()))
                .collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));

        //定义一个List作为最终返回的list
        List<CourseCategoryTreeDto> list1 = new ArrayList<>();

        //从头遍历List<CourseCategoryTreeDto>，一边遍历一边找子结点放在父节点的childrenTreeNodes
        courseCategoryTreeDtos.stream()
                .filter(item -> !id.equals(item.getId()))
                .forEach(item -> {

            //TODO 开始处理 向List写入元素
                    if (item.getParentid().equals(id)){

                        list1.add(item);
                    }

                    //找到节点的父结点
                    CourseCategoryTreeDto courseCategoryParent = mapTemp.get(item.getParentid());

                   if (courseCategoryParent != null){

                       //如果父结点的ChildrenTreeNodes属性为空
                       if (courseCategoryParent.getChildrenTreeNodes() == null){

                           courseCategoryParent.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                       }
                       //找到每个节点的子结点，放在父结点的childrenTreeNodes属性中
                       courseCategoryParent.getChildrenTreeNodes().add(item);
                   }


        });


        return list1;
    }
}
